<template>
  <div class="container add_edit">
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
      <el-form-item label="轮播图片" prop="img">
        <uni-file-picker
          ref="img"
          v-model="imageValue"
          fileMediatype="image"
          returnType="object"
          :image-styles="imageStyle"
          @success="imgUpload"
          @delete="imgDelete"
        />
        <div class="remark_txt">宽度 750px，高度 240px，大小建议几百KB左右</div>
      </el-form-item>
      <el-form-item label="跳转类型">
        <el-radio-group v-model="form.type">
          <el-radio value="网页">网页</el-radio>
          <el-radio value="页面">页面</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.type == '页面'" label="地址">
        <el-select v-model="mpPageUrl" placeholder="请选择" @change="urlChange">
          <el-option
            v-for="item in urlOptions"
            :key="item._id"
            :label="item.name + ' ' + item.url"
            :value="item._id"
          />
        </el-select>
        <div class="remark_txt">非必填</div>
      </el-form-item>
      <el-form-item label="跳转地址" prop="url" ref="url">
        <el-input v-model="form.url" placeholder="请输入跳转地址" clearable @clear="clearUrl" />
        <div class="dflex">
          <div class="remark_txt margin_r_50">自动获取上面选中的值</div>
          <div class="remark_txt" v-if="remark">{{ remark }}</div>
        </div>
      </el-form-item>
      <el-form-item label="排序">
        <el-input
          type="number"
          v-model.number="form.sort"
          :min="1"
          placeholder="请输入排序"
          clearable
          @input="value => (value = parseInt(value) || 1)"
        />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" placeholder="请输入备注" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch
          v-model="form.state"
          active-color="#ff6a6c"
          inactive-color="#bbb"
          active-value="启用"
          inactive-value="禁用"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          :loading="formLoading"
          round
          class="confirm-btn"
          @click="submitForm('ruleForm')"
        >
          <el-icon><Check /></el-icon>提交
        </el-button>
        <el-button round class="return-btn" @click="returnPage">
					<el-icon><Back /></el-icon>返回
				</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
	const __name = 'usemall-app-carousel'
	const __mpPage = 'usemall-app-wxmini-page'
	import { ref, reactive, getCurrentInstance, onMounted } from 'vue'

	// 获取 proxy 实例
	const { proxy } = getCurrentInstance()

	const dataId = ref('')
	const formLoading = ref(false)
	const form = reactive({
		img: '',
		type: '网页',
		url: '',
		sort: 0,
		remark: '',
		state: '启用'
	})
	const imageValue = ref(null)
	const imageStyle = {
		height: '200px',
		width: '500px'
	}
	const urlOptions = ref([])
	const remark = ref('')
	const mpPageUrl = ref('')
	const rules = reactive({
		img: [{ required: true, message: '请选择轮播图片', trigger: 'change' }],
		url: [{ required: true, message: '请输入跳转地址', trigger: 'change' }]
	})

	const loadData = async () => {
	  await proxy.$db[__mpPage].tolist().then(res => {
	    if (res.code === 200) {
	      res.datas.forEach(data => {
	        urlOptions.value.push(data)
	      })
	    }
	  })
	
	  if (!dataId.value) {
	    proxy.$db[__name].getsort().then(res => {
	      if (res.code === 200) {
	        form.sort = ++res.datas.sort
	      }
	    })
	    return
	  }
	
	  await proxy.$db[__name].tofirst(dataId.value).then(res => {
	    if (res.code === 200) {
	      for (let item in form) {
	        form[item] = res.datas[item]
	      }
	
	      if (form.img) {
	        imageValue.value = { url: form.img }
	      }
	    }
	  })
	}

	const submitForm = (formName) => {
		proxy.$refs[formName].validate((valid, obj) => {
			proxy.$api.set_unvalidated_form_focus(proxy, obj)
			if (valid) {
				formLoading.value = true
				if (!dataId.value) {
					proxy.$db[__name]
						.add(form)
						.then((res) => {
							if (res.code === 200) {
								proxy.getOpenerEventChannel().emit('loadData')
								returnPage()
							}
							formLoading.value = false
						})
						.catch(() => {
							formLoading.value = false
						})
				} else {
					proxy.$db[__name]
						.update(dataId.value, form)
						.then((res) => {
							if (res.code === 200) {
								proxy.getOpenerEventChannel().emit('loadData')
								returnPage()
							}
							formLoading.value = false
						})
						.catch(() => {
							formLoading.value = false
						})
				}
			}
		})
	}

	const imgUpload = (e) => {
		form.img = e.tempFilePaths[0]
		proxy.$refs.ruleForm.validateField('img')
	}

	const imgDelete = () => {
		imageValue.value = null
		form.img = ''
		proxy.$refs.ruleForm.validateField('img')
	}

	const returnPage = () => {
		proxy.$emit('closeTab')
		uni.redirectTo({
			url: '/pages/shop/home/page'
		})
		// proxy.$router.push('/pages/shop/home/page')
	}

	const urlChange = (data) => {
		const obj = urlOptions.value.find((x) => x._id === data)
		form.url = obj.url
		remark.value = obj.remark
	}

	const clearUrl = () => {
		mpPageUrl.value = ''
	}

	// 当组件挂载时加载数据
	onMounted(() => {
		dataId.value = proxy.$route.query.id || ''
		loadData()
	})
</script>

<style></style>
